/*
 * BusStationAPI.cpp
 *
 *  Created on: Jul 17, 2013
 *      Author: m
 */

#include "BusStationAPI.h"

using communication::ConcurrentMessageQueue;

namespace application
{

BusStationAPI::BusStationAPI( std::string ownerName ) :
    m_replyQueueName( BUS_STATION_REQUEST_BASENAME + ownerName ),
    m_replyChannel( new ConcurrentMessageQueue<BusStationReply>( m_replyQueueName ) )
{
}

// TODO: Ojo! Por ahora libero los recursos en el destructor, por ahí conviene liberarlos aparte!
BusStationAPI::~BusStationAPI()
{
}

void BusStationAPI::waitBus( Visitor& visitor, busStationType busStationType )
{
    BusStationPass pass;
    BusStationRequest request;
    BusStationReply reply;
    std::string replyQueueName;

    if ( busStationType == ENTRANCE_BUS_STATION )
    {
        pass = visitor.getTicket().m_entranceBusStationPass;
    }
    else
    {
        pass = visitor.getTicket().m_exitBusStationPass;
    }

    /*
     * Creo la cola en la que se van a escuchar las respuestas
     */
    replyQueueName = BUS_STATION_REQUEST_BASENAME + visitor.getId();
    ConcurrentMessageQueue<BusStationRequest>replyQueue( replyQueueName );

    /*
     * Configuro el pedido del visitante para ser encoladoen la sala
     */
    request.m_visitor = visitor.serialize();
    request.m_replyTo = replyQueueName;

    /*
     * Envio el pedido del visitante
     */
    ConcurrentMessageQueue<BusStationRequest>requestQueue( pass.m_busStationAddress );

    requestQueue.put( request );

    /*
     * Espero la respuesta
     */
    reply = m_replyChannel->get();

    switch ( reply.m_result )
    {
        case SUCCESS:
            visitor.setTicket( Ticket( reply.m_ticket ) );

            break;

        case INVALID_TICKET:
            throw Exception( "Invalid Ticket" );

        default:
            throw Exception();
    }
}

} /* namespace business */
